package com.peycard.servlet;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.peycard.common.FinancialTransactionsDTO;
import com.peycard.util.TransactionReceipt;

/**
 * Servlet implementation class Comprobante
 */
@Component
public class Comprobante extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Comprobante() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
	 * methods.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws Exception
	 */
	// invoked from doGet method to create PDF through servlet
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// Set content type to application / pdf
		// browser will open the document only if this is set
		response.setHeader("Content-Type", "application/pdf");
		// showing the pdf inline..meaning in the same window
		response.setHeader("Content-Disposition", "inline; filename="
				+ "reporte.pdf");
		FinancialTransactionsDTO dto = (FinancialTransactionsDTO) request
				.getAttribute("tx");
		// Get the output stream for writing PDF object
		TransactionReceipt receipt = new TransactionReceipt();
		OutputStream out = response.getOutputStream();
		receipt.generaPDF(out, dto);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public String getServletInfo() {
		return "This Servlet Generates PDF";
	}

}
